/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.alien.admin.modules.deploy.service.impl;

import com.alien.admin.modules.deploy.domain.DpJenkinsInstance;
import com.alien.admin.modules.system.domain.User;
import com.alien.admin.modules.system.repository.UserRepository;
import com.alien.admin.utils.*;
import lombok.RequiredArgsConstructor;
import com.alien.admin.modules.deploy.repository.DpJenkinsInstanceRepository;
import com.alien.admin.modules.deploy.service.DpJenkinsInstanceService;
import com.alien.admin.modules.deploy.service.dto.DpJenkinsInstanceDto;
import com.alien.admin.modules.deploy.service.dto.DpJenkinsInstanceQueryCriteria;
import com.alien.admin.modules.deploy.service.mapstruct.DpJenkinsInstanceMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
 * @author zengzhifang
 * @website https://el-admin.vip
 * @description 服务实现
 * @date 2021-09-13
 **/
@Service
@RequiredArgsConstructor
public class DpJenkinsInstanceServiceImpl implements DpJenkinsInstanceService {

    private final DpJenkinsInstanceRepository dpJenkinsInstanceRepository;
    private final DpJenkinsInstanceMapper dpJenkinsInstanceMapper;
    private final UserRepository userRepository;

    @Override
    public Map<String, Object> queryAll(DpJenkinsInstanceQueryCriteria criteria, Pageable pageable) {
        Page<DpJenkinsInstance> page = dpJenkinsInstanceRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(dpJenkinsInstanceMapper::toDto));
    }

    @Override
    public List<DpJenkinsInstanceDto> queryAll(DpJenkinsInstanceQueryCriteria criteria) {
        return dpJenkinsInstanceMapper.toDto(dpJenkinsInstanceRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public DpJenkinsInstanceDto findById(Integer id) {
        DpJenkinsInstance dpJenkinsInstance = dpJenkinsInstanceRepository.findById(id).orElseGet(DpJenkinsInstance::new);
        ValidationUtil.isNull(dpJenkinsInstance.getId(), "DpJenkinsInstance", "id", id);
        return dpJenkinsInstanceMapper.toDto(dpJenkinsInstance);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DpJenkinsInstanceDto create(DpJenkinsInstance resources) {

        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername());
        resources.setCreateBy(user.getUsername());
        resources.setUpdateBy(user.getUsername());
        resources.setCreateTime(timestamp);
        resources.setUpdateTime(timestamp);

        return dpJenkinsInstanceMapper.toDto(dpJenkinsInstanceRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DpJenkinsInstance resources) {
        DpJenkinsInstance dpJenkinsInstance = dpJenkinsInstanceRepository.findById(resources.getId()).orElseGet(DpJenkinsInstance::new);
        ValidationUtil.isNull(dpJenkinsInstance.getId(), "DpJenkinsInstance", "id", resources.getId());

        User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername());
        resources.setUpdateBy(user.getUsername());
        dpJenkinsInstance.setUpdateTime(new Timestamp(System.currentTimeMillis()));

        dpJenkinsInstance.copy(resources);

        dpJenkinsInstanceRepository.save(dpJenkinsInstance);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            dpJenkinsInstanceRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<DpJenkinsInstanceDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DpJenkinsInstanceDto dpJenkinsInstance : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("jenkins实例的名称", dpJenkinsInstance.getName());
            map.put("环境", dpJenkinsInstance.getEnv());
            map.put("jenkins实例的地址", dpJenkinsInstance.getUrl());
            map.put("操作jenkins使用的token", dpJenkinsInstance.getToken());
            map.put("创建人", dpJenkinsInstance.getCreateBy());
            map.put("修改人", dpJenkinsInstance.getUpdateBy());
            map.put("创建日期", dpJenkinsInstance.getCreateTime());
            map.put("更新时间", dpJenkinsInstance.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}